package com.shuyangyang.util;

import cn.hutool.core.util.StrUtil;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * Encrypt工具类
 *
 * @author YangYang Shu
 **/
public class EncryptUtil {

    private EncryptUtil() {
    }

    /**
     * Jasypt生成加密结果
     *
     * @param algorithm 加密算法
     * @param password  配置文件中设定的加密盐值
     * @param value     加密值
     * @return 加密结果
     */
    public static String enCryptPwd(String algorithm, String password, String value) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        encryptor.setConfig(crypto(algorithm, password));
        return encryptor.encrypt(value);
    }

    /**
     * 解密
     *
     * @param algorithm 加密算法
     * @param password  配置文件中设定的加密盐值
     * @param value     解密密文
     * @return 解密结果
     */
    public static String deCryptPwd(String algorithm, String password, String value) {
        PooledPBEStringEncryptor encrypt = new PooledPBEStringEncryptor();
        encrypt.setConfig(crypto(algorithm, password));
        return encrypt.decrypt(value);
    }

    /**
     * 设置配置属性
     *
     * @param algorithm 加密算法
     * @param password  密码
     * @return 配置
     */
    private static SimpleStringPBEConfig crypto(String algorithm, String password) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        if (StrUtil.isEmpty(algorithm)) {
            config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        } else {
            config.setAlgorithm(algorithm);
        }
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setProviderClassName(null);
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        return config;
    }
}
